import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {ApiUrl} from "../../../config/api-url";
import {BaseService} from "../../../shared/service/base.service";

@Component({
  selector: 'app-send-test-cmd',
  templateUrl: './send-test-cmd.component.html',
  styleUrls: ['./send-test-cmd.component.less']
})
export class SendTestCmdComponent implements OnInit {

  @Input()
  isVisible = false;
  @Input()
  inputDevice: any;


  constructor(private fb: FormBuilder, private baseService: BaseService) {
    this.buildForm();
  }

  ngOnInit(): void {

  }

  @Output()
  emitVisible: EventEmitter<any> = new EventEmitter();
  isOkLoading: any;
  isSpinning: any;

  // 模态框表单
  formModel: FormGroup;


  buildForm() {
    this.formModel = this.fb.group({
      cmd: [null, [Validators.required]],
    });
  }

  handleCancel() {
    this.isOkLoading = false;
    this.isSpinning = false;
    this.isVisible = false;
    this.emitVisible.emit(this.isVisible);
  }

  handleOk() {
    this.isOkLoading = true;
    this.isSpinning = true;

    for (const i in this.formModel.controls) {
      if (this.formModel.controls[i] != this.formModel.controls.user) {
        if (!this.formModel.controls[i].valid) {
          this.isOkLoading = false;
        }
      }
      this.formModel.controls[i].markAsDirty();
      this.formModel.controls[i].updateValueAndValidity();
    }

    console.log("cmd:" + this.formModel.value.cmd);

    let param = {
      deviceNo: this.inputDevice.deviceNo,
      cmd: this.formModel.value.cmd
    };

    this.baseService.post(ApiUrl.DeviceUrl + '/sendTestCmd', param).subscribe((res) => {
      if (res.status == 0) {
        this.isVisible = false;
        this.emitVisible.emit(this.isVisible);
        this.baseService.layer.messageSuccess('发送成功');
        this.formModel.get("cmd").setValue('');
      } else {
        this.baseService.layer.messageError('发送不成功：' + res.msg);
      }
      this.isOkLoading = false;
      this.isSpinning = false;
    });
  }
}
